<?php

namespace app\api\controller;

use think\Controller as ThinkController;
use app\api\model\Login as LoginModel;

/**
 * API控制器基类
 * Class BaseController
 * @package app\store\controller
 */
class Controller extends ThinkController
{
    const JSON_SUCCESS_STATUS = 1;
    const JSON_ERROR_STATUS = 0;

    /**
     * 返回封装后的 API 数据到客户端
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderJson($code = self::JSON_SUCCESS_STATUS, $msg = '', $data = [])
    {
        return compact('code', 'msg', 'data');
    }

    /**
     * 返回操作成功json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderSuccess($data = [], $msg = 'success')
    {
        return $this->renderJson(self::JSON_SUCCESS_STATUS, $msg, $data);
    }

    /**
     * 返回操作失败json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderError($msg = 'error', $data = [])
    {
        return $this->renderJson(self::JSON_ERROR_STATUS, $msg, $data);
    }

    /**
     * 获取post数据 (数组)
     * @param $key
     * @return mixed
     */
    protected function postData($key)
    {
        return $this->request->post($key . '/a');
    }

    /**
     * 输出错误信息
     * @param int $code
     * @param $msg
     * @throws BaseException
     */
    protected function throwError($msg, $code = 0)
    {
        throw new BaseException(['code' => $code, 'msg' => $msg]);
    }

    /**
     * APP接口开发中提供的json形式
     * @param string $code
     * @param string $message
     * @param array $date
     * @return false|string
     */
    protected function json($code = '', $message = '', $date = [])
    {
        $result = array(
            'code' => $code,
            'message' => $message,
            'content' => $date
        );
        return json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取当前用户信息
     * @param bool $is_force
     * @return UserModel|bool|null
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    protected function getUser($is_force = true)
    {
        if (!$token = $this->request->param('token')) {
            echo json_encode(['code' => 0, 'msg' => '您未登录，无法确认身份'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        if (!$user = LoginModel::getUser($token)) {
            echo json_encode(['code' => 0, 'msg' => '没有找到用户信息'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        return $user;
    }
}
